package com.zhouheng.springbootmultithreading.module.task;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 多线程异步算法处理配置
 *
 * @author 周恒
 * @date 20181107
 * @since v1.0
 */
@Configuration
@EnableAsync
public class ThreadAsyncConfig {

    /**
     * 异步线程池
     *
     * @return 返回 thread pool task executor 描述此返回参数
     * @author LeoRmAo
     * @date 20190905 11:00:21
     * @since v1.0
     */
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(16);
        //设置最大线程数
        threadPool.setMaxPoolSize(42);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(0);
        //等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        //等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(30);
        //线程名称前缀
        threadPool.setThreadNamePrefix("async-");
        //初始化线程
        threadPool.initialize();
        return threadPool;
    }

}

